window.selCheckedNum = 1;
const organization = this.pageObj.getApiWidgetByAliasName('tree_organization');
const search_input = this.pageObj.getApiWidgetByAliasName('search_input');
const three = this.pageObj.getApiWidgetByAliasName('三维组件');
const prefix = this.pageObj.getVariables().find(v => v.name === 'environmentType')?.value || '';
const text = $(search_input.__box).find('.input-filter').val();

const orgBtn = this.pageObj.getApiWidgetByAliasName('org_btn');
const groupBtn = this.pageObj.getApiWidgetByAliasName('group_btn');
const deviceBtn = this.pageObj.getApiWidgetByAliasName('device_btn');

const type = this.pageObj.getApiWidgetByAliasName('type_selection');
const select = type.widgetObj.getChecked()?.value;


$(this.__box).css("box-shadow", "inset 0 -5px 8px var(--active-color)");
$(groupBtn.__box).css("box-shadow", "inset 0 0 5px var(--body-bg)");
$(deviceBtn.__box).css("box-shadow", "inset 0 0 5px var(--body-bg)");

console.log('type_selection', type);

let fetchUrl = `/${prefix}Communication/pubCommunicationAccount/getOrgListByName`

if (text) {
    fetchUrl = `${fetchUrl}?communicationName=${text}`
}

fetch(fetchUrl).then(res => res.json()).then(res => {
    const { result, resultCode } = res;
    if (resultCode === '000000') {
        const artemis = three.widgetObj.artemis;
        const dataSource = result.map(breakDataSource);
        if (select === 'all') {
            organization.widgetObj._option.dataSource = artemis.resetUsersStatus(dataSource);
        } else {
            organization.widgetObj._option.dataSource = artemis.filterUsersOnline(dataSource);
        }

        organization.widgetObj.render();
        console.log(organization.widgetObj._option.dataSource)
    }
});


function resetMember (member, index) {
    return {
        ...member,
        type: '1',
        title: `${member.personName || member.communicationName || `匿名${index}`}(${member.account})`,
        username: `${member.personName || member.communicationName || `匿名${index}`}`,
        userId: member.account,
        treeId: member.id || member.personId,
    }
}

const random = (num = 10) => parseInt(Math.random() * Math.pow(10, num))

function breakDataSource(item) {
    const dispatchLength = item.dispatchList?.length
    item.title = `${item.orgName}[${item.count}]`;
    item.id = item.orgId;
    item.treeId = item.orgId;
    if (item.children) {
        item.children = item.children.map(breakDataSource);
        item.type = '0'
    }

    if (dispatchLength) {
        const id = `${random(10)}-${random(10)}`;
        item.children.unshift({
            id,
            treeId: id,
            title: `调度台[${dispatchLength}]`,
            children: item.dispatchList.map(resetMember),
        })
    }

    if (item.personList) {
        item.personList.map((member, index) => {
            item.children.push(resetMember(member, index))
        });
    }

    return item
}